Implementing User Authentication
Table of Contents
Introducing Sessions and Session Variables
The tricky part in the user authentication framework is how to flag a user across all website pages as logged in or not logged in, especially given your knowledge that the server forgets users and all their data in between every page request. In some cases, you may have overcome the server's forgetfulness by sending URL (or query string) and form variables between pages; this is a core capability of ASP, ColdFusion, and PHP. But these solutions are temporary, requiring you to manually send data to every page that needs it. It is better to use something more persistent.
One type of persistent variable is the cookie. A cookie is a name-value pair stored on the user's hard drive and sent to the server when the user makes an HTTP request. Using this technique, you can simulate the effect of the server remembering a user across multiple pages, simply by having pages use and respond to cookie data.
In large part to facilitate applications that need to keep track of users and data over time, ASP, ColdFusion, and PHP have special built-in features that handle much of this work for you. One of these is the session variable scope. Session variables contain information for a single user in a single session. If the user leaves the site or closes the browser for a period of time (usually about 20 minutes), then the session ends, and the application flushes the information from the server's memory.
The session variable is perfect for handling the login flag. That is, once a user successfully logs in, the application sets a session variable indicating the successful log-on. Each page that restricts access needs merely to check for the presence of this session variable to determine whether to grant access to the page or redirect the user to a different page.
For the data to be persistent, you must store it somewhere. You typically store session variables as cookies on the user's computer and match them to temporary session variables stored on the server. The storage of data in two locations and its subsequent matching is usually invisible to the developer; that is, while you may set and retrieve session variables, for example, you won't be both setting and retrieving server and cookie variables, because that happens behind the scenes.
From even this brief overview, you can understand why a session management framework is so important to authentication. It enables a single entry through a login page to provide access to multiple pages, without requiring the developer to manually create scripts that send the data from each page to the next.